package com.okay.popwindow

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.okay.testclass.R
import com.okay.util.DensityUtils.dp2px

class PopWindowView {

    private var popWindow: PopupWindow? = null
    private var recyclerView :RecyclerView? = null

    /**
     * 初始化弹出弹窗
     * @param context
     * @param parentView   基准view的父view
     * @param v   需要弹出弹窗的基准view
     * @param list   列表数据
     * @param iMsgPopClick  点击事件的回调
     */
    fun initPopWindow(
        context: Context,
        parentView: View,
        v: View,
        list: List<ClassRelation>,
        iMsgPopClick: IMsgPopClick?
    ) {
        val view: View = LayoutInflater.from(context).inflate(R.layout.item_popup, null, false)
        recyclerView = view.findViewById<RecyclerView>(R.id.recycle)
        var popWinBg = view.findViewById<CardView>(R.id.pop_win_bg)
        recyclerView?.let {
            //获取出recycler的高度
            var hh = (list.size*dp2px(context,32f))+dp2px(context,20f)
            //设置弹窗的最大高度
            var hh2 =dp2px(context,180f)
            var ll = popWinBg.layoutParams
            if(hh>hh2){//谁的值小，就用谁
                ll.height = hh2
            }else{
                ll.height = hh
            }
            popWinBg.layoutParams = ll

            val adapter = PopRecyclerAdapter(it)
            it.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            //        recyclerView.setItemAnimator(new DefaultItemAnimator());
            it.itemAnimator = null
            it.adapter = adapter
            adapter.setData(list)
            //设置点击事件
            adapter.setItemListener(object : PopRecyclerAdapter.onRecyclerItemClickerListener {
                override fun onRecyclerItemClick(view: View?, data: Any?, position: Int) {
                    iMsgPopClick?.onMsgPopClick(data)
                    popWindow?.dismiss()
                }
            })
        }

        //1.构造一个PopupWindow，参数依次是加载的View，宽高
        popWindow = PopupWindow(
            view,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true
        )
        popWindow?.let {
            it.animationStyle = R.anim.anim_pop //设置加载动画

            //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
            //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
            //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
            it.isTouchable = true
            it.setTouchInterceptor { v, event ->
                false
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
            it.setBackgroundDrawable(ColorDrawable(0x00000000)) //要为popWindow设置一个背景才有效
            it.contentView.measure(
                makeDropDownMeasureSpec(it.width),
                makeDropDownMeasureSpec(it.height)
            )
            val bool: Boolean = calculatePopWindowPos(parentView, v, it.contentView)

//        int offsetX = Math.abs(popWindow.getContentView().getMeasuredWidth()-v.getWidth()) / 2;
            val offsetX = -((it.contentView.measuredWidth - v.width) / 2)
            val offsetY = -(it.contentView.measuredHeight + v.height)

            //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
            if (bool) { //显示在view的下方
                it.showAsDropDown(v, offsetX, 0)
            } else {
                it.showAsDropDown(v, offsetX, offsetY)
            }
        }
    }

    /**
     * 刷新数据
     */
    fun freshData(list: List<ClassRelation>){
        recyclerView?.let {
            (it.adapter as PopRecyclerAdapter)?.setData(list)
        }
        popWindow?.let {
            it.update()
        }
    }

    private fun makeDropDownMeasureSpec(measureSpec: Int): Int {
        val mode: Int = if (measureSpec == ViewGroup.LayoutParams.WRAP_CONTENT) {
            View.MeasureSpec.UNSPECIFIED
        } else {
            View.MeasureSpec.EXACTLY
        }
        return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), mode)
    }

    /**
     * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
     *
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    private fun calculatePopWindowPos(
        parentView: View,
        anchorView: View,
        contentView: View
    ): Boolean {
        val anchorLoc = IntArray(2)
        val anchorLoc1 = IntArray(2)
        // 获取锚点View在父布局中的坐标
        anchorView.getLocationInWindow(anchorLoc) //这个方法获取的应该是子view距离父view的方法，但是获取出来是距离屏幕边缘的距离，
        parentView.getLocationInWindow(anchorLoc1)

        // 计算contentView的高宽
        val windowHeight = contentView.measuredHeight
        val windowWidth = contentView.measuredWidth
        // 判断需要向上弹出还是向下弹出显示
        return anchorLoc[1] - anchorLoc1[1] < windowHeight //是否显示在下方
    }

    interface IMsgPopClick {
        fun onMsgPopClick(data: Any?)
    }
}